package utils

import (
	"bufio"
	"os"
	"strconv"
	"strings"
	"sync"
)

// Config 应用程序配置
type Config struct {
	// 功能模块控制
	Features struct {
		TransferEnabled bool
		ClientEnabled   bool
		ServerEnabled   bool
		ToolsEnabled    bool
		NotepadEnabled  bool
	}

	// 转发功能配置
	Transfer struct {
		BufferSize      int
		ReadTimeout     int
		WriteTimeout    int
		MaxConnections  int
		ConnectionReuse bool
	}

	// 服务器配置
	Server struct {
		DefaultPort         int
		MaxClients          int
		BroadcastBufferSize int
	}

	// 性能配置
	Performance struct {
		EnableMonitoring    bool
		StatsUpdateInterval int
		DebugLogging        bool
	}

	mutex sync.RWMutex
}

var globalConfig *Config
var configOnce sync.Once

// GetConfig 获取全局配置实例
func GetConfig() *Config {
	configOnce.Do(func() {
		globalConfig = &Config{}
		globalConfig.setDefaults()
		globalConfig.loadFromFile("config.ini")
		globalConfig.validate()
	})
	return globalConfig
}

// setDefaults 设置默认配置
func (c *Config) setDefaults() {
	c.mutex.Lock()
	defer c.mutex.Unlock()

	// 默认只启用转发功能
	c.Features.TransferEnabled = true
	c.Features.ClientEnabled = false
	c.Features.ServerEnabled = false
	c.Features.ToolsEnabled = false
	c.Features.NotepadEnabled = false

	// 转发功能默认配置
	c.Transfer.BufferSize = 8192
	c.Transfer.ReadTimeout = 300
	c.Transfer.WriteTimeout = 30
	c.Transfer.MaxConnections = 1000
	c.Transfer.ConnectionReuse = true

	// 服务器默认配置
	c.Server.DefaultPort = 8088
	c.Server.MaxClients = 500
	c.Server.BroadcastBufferSize = 1000

	// 性能默认配置
	c.Performance.EnableMonitoring = true
	c.Performance.StatsUpdateInterval = 1
	c.Performance.DebugLogging = false
}

// loadFromFile 从文件加载配置
func (c *Config) loadFromFile(filename string) {
	file, err := os.Open(filename)
	if err != nil {
		// 如果文件不存在，使用默认配置
		return
	}
	defer file.Close()

	c.mutex.Lock()
	defer c.mutex.Unlock()

	scanner := bufio.NewScanner(file)
	currentSection := ""

	for scanner.Scan() {
		line := strings.TrimSpace(scanner.Text())

		// 跳过空行和注释
		if line == "" || strings.HasPrefix(line, "#") {
			continue
		}

		// 处理节（section）
		if strings.HasPrefix(line, "[") && strings.HasSuffix(line, "]") {
			currentSection = strings.Trim(line, "[]")
			continue
		}

		// 处理键值对
		if strings.Contains(line, "=") {
			parts := strings.SplitN(line, "=", 2)
			if len(parts) != 2 {
				continue
			}

			key := strings.TrimSpace(parts[0])
			value := strings.TrimSpace(parts[1])

			c.setValue(currentSection, key, value)
		}
	}
}

// setValue 设置配置值
func (c *Config) setValue(section, key, value string) {
	switch section {
	case "features":
		c.setFeatureValue(key, value)
	case "transfer":
		c.setTransferValue(key, value)
	case "server":
		c.setServerValue(key, value)
	case "performance":
		c.setPerformanceValue(key, value)
	}
}

// setFeatureValue 设置功能模块配置
func (c *Config) setFeatureValue(key, value string) {
	boolValue := strings.ToLower(value) == "true"

	switch key {
	case "transfer_enabled":
		c.Features.TransferEnabled = boolValue
	case "client_enabled":
		c.Features.ClientEnabled = boolValue
	case "server_enabled":
		c.Features.ServerEnabled = boolValue
	case "tools_enabled":
		c.Features.ToolsEnabled = boolValue
	case "notepad_enabled":
		c.Features.NotepadEnabled = boolValue
	}
}

// setTransferValue 设置转发功能配置
func (c *Config) setTransferValue(key, value string) {
	switch key {
	case "buffer_size":
		if intValue, err := strconv.Atoi(value); err == nil {
			c.Transfer.BufferSize = intValue
		}
	case "read_timeout":
		if intValue, err := strconv.Atoi(value); err == nil {
			c.Transfer.ReadTimeout = intValue
		}
	case "write_timeout":
		if intValue, err := strconv.Atoi(value); err == nil {
			c.Transfer.WriteTimeout = intValue
		}
	case "max_connections":
		if intValue, err := strconv.Atoi(value); err == nil {
			c.Transfer.MaxConnections = intValue
		}
	case "connection_reuse":
		c.Transfer.ConnectionReuse = strings.ToLower(value) == "true"
	}
}

// setServerValue 设置服务器配置
func (c *Config) setServerValue(key, value string) {
	switch key {
	case "default_port":
		if intValue, err := strconv.Atoi(value); err == nil {
			c.Server.DefaultPort = intValue
		}
	case "max_clients":
		if intValue, err := strconv.Atoi(value); err == nil {
			c.Server.MaxClients = intValue
		}
	case "broadcast_buffer_size":
		if intValue, err := strconv.Atoi(value); err == nil {
			c.Server.BroadcastBufferSize = intValue
		}
	}
}

// setPerformanceValue 设置性能配置
func (c *Config) setPerformanceValue(key, value string) {
	switch key {
	case "enable_monitoring":
		c.Performance.EnableMonitoring = strings.ToLower(value) == "true"
	case "stats_update_interval":
		if intValue, err := strconv.Atoi(value); err == nil {
			c.Performance.StatsUpdateInterval = intValue
		}
	case "debug_logging":
		c.Performance.DebugLogging = strings.ToLower(value) == "true"
	}
}

// IsFeatureEnabled 检查功能是否启用
func (c *Config) IsFeatureEnabled(feature string) bool {
	c.mutex.RLock()
	defer c.mutex.RUnlock()

	switch feature {
	case "transfer":
		return c.Features.TransferEnabled
	case "client":
		return c.Features.ClientEnabled
	case "server":
		return c.Features.ServerEnabled
	case "tools":
		return c.Features.ToolsEnabled
	case "notepad":
		return c.Features.NotepadEnabled
	default:
		return false
	}
}

// GetTransferConfig 获取转发配置
func (c *Config) GetTransferConfig() struct {
	BufferSize      int
	ReadTimeout     int
	WriteTimeout    int
	MaxConnections  int
	ConnectionReuse bool
} {
	c.mutex.RLock()
	defer c.mutex.RUnlock()
	return c.Transfer
}

// GetServerConfig 获取服务器配置
func (c *Config) GetServerConfig() struct {
	DefaultPort         int
	MaxClients          int
	BroadcastBufferSize int
} {
	c.mutex.RLock()
	defer c.mutex.RUnlock()
	return c.Server
}

// GetPerformanceConfig 获取性能配置
func (c *Config) GetPerformanceConfig() struct {
	EnableMonitoring    bool
	StatsUpdateInterval int
	DebugLogging        bool
} {
	c.mutex.RLock()
	defer c.mutex.RUnlock()
	return c.Performance
}

// GetEnabledFeatures 获取已启用的功能列表
func (c *Config) GetEnabledFeatures() map[string]bool {
	c.mutex.RLock()
	defer c.mutex.RUnlock()

	return map[string]bool{
		"transfer": c.Features.TransferEnabled,
		"client":   c.Features.ClientEnabled,
		"server":   c.Features.ServerEnabled,
		"tools":    c.Features.ToolsEnabled,
		"notepad":  c.Features.NotepadEnabled,
	}
}

// validate 验证配置的有效性
func (c *Config) validate() {
	c.mutex.Lock()
	defer c.mutex.Unlock()

	// 验证转发配置
	if c.Transfer.BufferSize < 1024 {
		GetLogger().Warn("缓冲区大小过小，设置为默认值8192")
		c.Transfer.BufferSize = 8192
	}
	if c.Transfer.BufferSize > 64*1024 {
		GetLogger().Warn("缓冲区大小过大，设置为64KB")
		c.Transfer.BufferSize = 64 * 1024
	}

	if c.Transfer.ReadTimeout < 1 {
		GetLogger().Warn("读取超时时间过短，设置为默认值300秒")
		c.Transfer.ReadTimeout = 300
	}
	if c.Transfer.WriteTimeout < 1 {
		GetLogger().Warn("写入超时时间过短，设置为默认值30秒")
		c.Transfer.WriteTimeout = 30
	}

	if c.Transfer.MaxConnections < 1 {
		GetLogger().Warn("最大连接数过少，设置为默认值1000")
		c.Transfer.MaxConnections = 1000
	}
	if c.Transfer.MaxConnections > 10000 {
		GetLogger().Warn("最大连接数过多，设置为10000")
		c.Transfer.MaxConnections = 10000
	}

	// 验证服务器配置
	if c.Server.DefaultPort < 1 || c.Server.DefaultPort > 65535 {
		GetLogger().Warn("默认端口无效，设置为8080")
		c.Server.DefaultPort = 8088
	}

	if c.Server.MaxClients < 1 {
		GetLogger().Warn("最大客户端数过少，设置为默认值500")
		c.Server.MaxClients = 500
	}

	if c.Server.BroadcastBufferSize < 100 {
		GetLogger().Warn("广播缓冲区大小过小，设置为默认值1000")
		c.Server.BroadcastBufferSize = 1000
	}

	// 验证性能配置
	if c.Performance.StatsUpdateInterval < 1 {
		GetLogger().Warn("统计信息更新间隔过短，设置为默认值1秒")
		c.Performance.StatsUpdateInterval = 1
	}

	GetLogger().Info("配置验证完成")
}
